import { Router } from 'express';
import { body, param, query } from 'express-validator';
import { authenticateToken, authorizeRole } from '../middleware/auth';
import { validateRequest } from '../middleware/validation';
import { hashPassword } from '../lib/auth';
import { prisma } from '../lib/prisma';

const router = Router();

// 获取用户列表
router.get('/', 
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('search').optional().isString().trim(),
    query('role').optional().isIn(['ADMIN', 'EDITOR', 'VIEWER']),
    query('status').optional().isIn(['ACTIVE', 'INACTIVE', 'BANNED'])
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { page = 1, limit = 20, search, role, status } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      // 构建查询条件
      const where: any = {};
      if (search) {
        where.OR = [
          { username: { contains: search as string, mode: 'insensitive' } },
          { email: { contains: search as string, mode: 'insensitive' } }
        ];
      }
      if (role) where.role = role;
      if (status) where.status = status;

      // 查询用户
      const [users, total] = await Promise.all([
        prisma.user.findMany({
          where,
          select: {
            id: true,
            username: true,
            email: true,
            role: true,
            avatar: true,
            status: true,
            lastLoginAt: true,
            createdAt: true,
            updatedAt: true,
            _count: {
              select: {
                knowledgeBases: true,
                uploads: true
              }
            }
          },
          skip,
          take: Number(limit),
          orderBy: { createdAt: 'desc' }
        }),
        prisma.user.count({ where })
      ]);

      res.json({
        code: 200,
        message: '获取用户列表成功',
        data: {
          users,
          pagination: {
            page: Number(page),
            limit: Number(limit),
            total,
            pages: Math.ceil(total / Number(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取用户列表失败:', error);
      res.status(500).json({ success: false, error: '获取用户列表失败' });
    }
  }
);

// 获取单个用户
router.get('/:id',
  authenticateToken,
  [
    param('id').isString().notEmpty().withMessage('用户ID不能为空')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const user = await prisma.user.findUnique({
        where: { id },
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          avatar: true,
          status: true,
          lastLoginAt: true,
          createdAt: true,
          updatedAt: true,
          knowledgeBases: {
            select: {
              id: true,
              title: true,
              status: true,
              createdAt: true
            },
            orderBy: { createdAt: 'desc' },
            take: 10
          },
          uploads: {
            select: {
              id: true,
              filename: true,
              originalName: true,
              createdAt: true
            },
            orderBy: { createdAt: 'desc' },
            take: 10
          }
        }
      });

      if (!user) {
        return res.status(404).json({ success: false, error: '用户不存在' });
      }

      res.json({ code: 200, message: '获取用户信息成功', data: user });
    } catch (error) {
      console.error('获取用户信息失败:', error);
      res.status(500).json({ success: false, error: '获取用户信息失败' });
    }
  }
);

// 创建用户
router.post('/',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    body('username').isString().trim().isLength({ min: 3, max: 50 }).withMessage('用户名长度必须在3-50个字符之间'),
    body('email').isEmail().withMessage('邮箱格式不正确'),
    body('password').isString().isLength({ min: 6 }).withMessage('密码长度至少6个字符'),
    body('role').optional().isIn(['ADMIN', 'EDITOR', 'VIEWER']).withMessage('角色无效'),
    body('status').optional().isIn(['ACTIVE', 'INACTIVE', 'BANNED']).withMessage('状态无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { username, email, password, role = 'VIEWER', status = 'ACTIVE' } = req.body;

      // 检查用户名和邮箱是否已存在
      const existingUser = await prisma.user.findFirst({
        where: {
          OR: [{ username }, { email }]
        }
      });

      if (existingUser) {
        return res.status(400).json({ 
          success: false, 
          error: existingUser.username === username ? '用户名已存在' : '邮箱已存在' 
        });
      }

      // 创建用户
      const hashedPassword = await hashPassword(password);
      const user = await prisma.user.create({
        data: {
          username,
          email,
          password: hashedPassword,
          role,
          status
        },
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          status: true,
          createdAt: true
        }
      });

      res.status(201).json({ code: 200, message: '用户创建成功', data: user });
    } catch (error) {
      console.error('创建用户失败:', error);
      res.status(500).json({ success: false, error: '创建用户失败' });
    }
  }
);

// 更新用户
router.put('/:id',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    param('id').isString().notEmpty().withMessage('用户ID不能为空'),
    body('username').optional().isString().trim().isLength({ min: 3, max: 50 }).withMessage('用户名长度必须在3-50个字符之间'),
    body('email').optional().isEmail().withMessage('邮箱格式不正确'),
    body('role').optional().isIn(['ADMIN', 'EDITOR', 'VIEWER']).withMessage('角色无效'),
    body('status').optional().isIn(['ACTIVE', 'INACTIVE', 'BANNED']).withMessage('状态无效'),
    body('avatar').optional().isString().trim()
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const updateData = req.body;

      // 检查用户是否存在
      const existingUser = await prisma.user.findUnique({ where: { id } });
      if (!existingUser) {
        return res.status(404).json({ success: false, error: '用户不存在' });
      }

      // 如果要更新用户名或邮箱，检查是否重复
      if (updateData.username || updateData.email) {
        const duplicateUser = await prisma.user.findFirst({
          where: {
            OR: [
              ...(updateData.username ? [{ username: updateData.username }] : []),
              ...(updateData.email ? [{ email: updateData.email }] : [])
            ],
            NOT: { id }
          }
        });

        if (duplicateUser) {
          return res.status(400).json({ 
            success: false, 
            error: duplicateUser.username === updateData.username ? '用户名已存在' : '邮箱已存在' 
          });
        }
      }

      // 更新用户
      const user = await prisma.user.update({
        where: { id },
        data: updateData,
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          status: true,
          avatar: true,
          updatedAt: true
        }
      });

      res.json({ code: 200, message: '用户更新成功', data: user });
    } catch (error) {
      console.error('更新用户失败:', error);
      res.status(500).json({ success: false, error: '更新用户失败' });
    }
  }
);

// 删除用户
router.delete('/:id',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    param('id').isString().notEmpty().withMessage('用户ID不能为空')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;

      // 检查用户是否存在
      const existingUser = await prisma.user.findUnique({ where: { id } });
      if (!existingUser) {
        return res.status(404).json({ success: false, error: '用户不存在' });
      }

      // 不能删除自己
      if (id === req.user.id) {
        return res.status(400).json({ success: false, error: '不能删除自己的账户' });
      }

      // 删除用户（级联删除相关数据）
      await prisma.user.delete({ where: { id } });

      res.json({ code: 200, message: '用户删除成功', data: null });
    } catch (error) {
      console.error('删除用户失败:', error);
      res.status(500).json({ success: false, error: '删除用户失败' });
    }
  }
);

// 重置用户密码
router.post('/:id/reset-password',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    param('id').isString().notEmpty().withMessage('用户ID不能为空'),
    body('newPassword').isString().isLength({ min: 6 }).withMessage('新密码长度至少6个字符')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const { newPassword } = req.body;

      // 检查用户是否存在
      const existingUser = await prisma.user.findUnique({ where: { id } });
      if (!existingUser) {
        return res.status(404).json({ success: false, error: '用户不存在' });
      }

      // 重置密码
      const hashedPassword = await hashPassword(newPassword);
      await prisma.user.update({
        where: { id },
        data: { password: hashedPassword }
      });

      res.json({ code: 200, message: '密码重置成功', data: null });
    } catch (error) {
      console.error('重置密码失败:', error);
      res.status(500).json({ success: false, error: '重置密码失败' });
    }
  }
);

// 获取用户统计信息
router.get('/stats/overview',
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res) => {
    try {
      const [
        totalUsers,
        activeUsers,
        bannedUsers,
        usersByRole,
        recentUsers
      ] = await Promise.all([
        prisma.user.count(),
        prisma.user.count({ where: { status: 'ACTIVE' } }),
        prisma.user.count({ where: { status: 'BANNED' } }),
        prisma.user.groupBy({
          by: ['role'],
          _count: { role: true }
        }),
        prisma.user.findMany({
          select: {
            id: true,
            username: true,
            email: true,
            role: true,
            createdAt: true
          },
          orderBy: { createdAt: 'desc' },
          take: 5
        })
      ]);

      res.json({
        code: 200,
        message: '获取用户统计成功',
        data: {
          totalUsers,
          activeUsers,
          bannedUsers,
          usersByRole,
          recentUsers
        }
      });
    } catch (error) {
      console.error('获取用户统计失败:', error);
      res.status(500).json({ success: false, error: '获取用户统计失败' });
    }
  }
);

export { router as userRoutes };
